﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MySql.Data.MySqlClient;
using System.Data.Odbc;
using System.Collections.Specialized;

///<Summary>
///Satura rādītāja lapa
///</Summary>
namespace EuroAudit
{
    public partial class Index : System.Web.UI.Page
    {
        GlobalF GFunc = new GlobalF();
        //funkcija zaru pievienošanai no norādītās tabulas
        void LoadNodesFromTable(ref TreeNode BaseNode, string BaseNodePath, string QueryString)
        {
            //QString piemērs - SELECT NosID as NodeID, Nos as NodeText, 1 as ViewID, 'DocList.aspx' as ViewParam FROM spr WHERE RecStatus=0 #Authorization# ORDER BY Nos
            //QString mainīgie-#Authorization#
            string QString = QueryString;
            string QStringSN = "";
            string AuthString = " AND (AccessU LIKE '%;guest;%' OR AccessG LIKE '%;Everyone;%' OR AccessG LIKE '%;Guests;%' OR AccessG LIKE '%;Authenticated users;%' " + Session["WhereGroups"] + ")";
            string AuthStringNA = " AND (AccessU LIKE '%;guest;%' OR AccessG LIKE '%;Everyone;%' OR AccessG LIKE '%;Guests;%')";
            DataSet dsTable;
            DataSet dsSubNodes;
            TreeNode ChildNode;
            TreeNode ChildSubNode;
            string NodePathLoaded="xxx";

            try
            {
                if (Session["IsAdmin"].ToString() == "1")
                {
                    QString = QString.Replace("#Authorization#", "");
                    QStringSN = "SELECT * FROM tcontent WHERE RecStatus=0 AND NodePath LIKE '" + BaseNodePath + "/%' ORDER BY NodePath";
                }
                else
                {
                    if (Session["UserName"] == null || Session["UserName"].ToString() == "" || Session["UserName"].ToString() == "guest")
                    {

                        QString = QString.Replace("#Authorization#", AuthStringNA);
                        QStringSN = "SELECT * FROM tcontent WHERE RecStatus=0 AND NodePath LIKE '" + BaseNodePath + "/%' " + AuthStringNA + " ORDER BY NodePath";
                    }
                    else
                    {
                        QString = QString.Replace("#Authorization#", AuthString);
                        QStringSN = "SELECT * FROM tcontent WHERE RecStatus=0 AND NodePath LIKE '" + BaseNodePath + "/%' " + AuthString + " ORDER BY NodePath";
                    }
                }
                dsTable = GFunc.GetData(QString, "WebCNS", false);

                //pieprasam apakšzarus
                dsSubNodes = GFunc.GetData(QStringSN, "WebCNS", false);

                if (dsTable.Tables.Count > 0)
                {
                    if (dsTable.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow row in dsTable.Tables[0].Rows)
                        {
                            ChildNode = new TreeNode(row["NodeText"].ToString(), row["NodeID"].ToString());
                            BaseNode.ChildNodes.Add(ChildNode);
                            ChildNode.SelectAction = TreeNodeSelectAction.SelectExpand;
                            ChildNode.Collapse();
                            ChildNode.NavigateUrl = "main.aspx?ViewID=" + row["ViewID"].ToString() + "&NodePath=" + BaseNodePath + "/" + row["NodeID"].ToString() + "&ViewParam=" + row["ViewParam"].ToString() + "&NodeText=" + ChildNode.Text.ToLower();
                            ChildNode.Target = "main";
                            if (dsSubNodes.Tables.Count > 0)
                            {
                                if (dsSubNodes.Tables[0].Rows.Count > 0)
                                {
                                    foreach (DataRow rowSN in dsSubNodes.Tables[0].Rows)
                                    {
                                        ChildSubNode = new TreeNode(rowSN["TContName"].ToString(), rowSN["NodeID"].ToString());
                                        ChildNode.ChildNodes.Add(ChildSubNode);
                                        ChildSubNode.SelectAction = TreeNodeSelectAction.SelectExpand;
                                        ChildSubNode.NavigateUrl = "main.aspx?ViewID=" + rowSN["ViewID"].ToString() + "&NodePath=" + BaseNodePath + "/" + row["NodeID"].ToString()+"/"+rowSN["NodeID"].ToString() + "&ViewParam=" + rowSN["ViewParam"].ToString() + "&NodeText=" + ChildSubNode.Text.ToLower();
                                        ChildSubNode.Target = "main";
                                        if (rowSN["ViewID"].ToString() == "3")
                                        {
                                            NodePathLoaded = rowSN["NodePath"].ToString();
                                            LoadNodesFromTable(ref ChildSubNode, BaseNodePath + "/" + row["NodeID"].ToString() + "/" + rowSN["NodeID"].ToString(), rowSN["ViewParam"].ToString());

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            TreeNode ParentNode;
            string QString="";
            int UserEditBranch = 0;
            string NodePathLoaded = "xxx";

            try
            {
                tvContent.Nodes.Clear();
                if (Session["UserName"] == null || Session["UserName"].ToString() == "" || Session["UserName"].ToString() == "guest")
                {
                    cmdAuth.Text = "Autorizācija";
                    //Response.Write("Guest content.");
                    //Response.End();
                    
                    QString = "SELECT * FROM tcontent WHERE RecStatus=0 AND (AccessU LIKE '%;guest;%' OR AccessG LIKE '%;Guests;%' OR AccessG LIKE '%;Everyone;%') ORDER BY NodePath;"; //"SELECT * FROM tcontent WHERE AccessU LIKE '%;Guest;%' OR AccessG LIKE '%;Guests;%' OR AccessG LIKE '%;Everyone;%' ORDER BY substring_index(NodePath,'/',2),NodeID;";
                    Session["UserName"] = "guest";
                    Session["UserGroups"] = ";Guests;";
                    Session["WhereGroups"] = " OR AccessG LIKE '%;Guests;' OR AccessG LIKE '%;Everyone;%' ";
                    Session["IsAdmin"] = "0";
                    //dsLogin.Select(DataSourceSelectArguments.Empty);
                     
                }
                else
                {
                    cmdAuth.Text = "Izlogoties";
                    //Response.Write(Session["UserName"] + " content.");
                    if (Session["IsAdmin"].ToString() == "1")
                    {
                        QString = "SELECT * FROM tcontent WHERE RecStatus=0 ORDER BY NodePath;"; //"SELECT * FROM tcontent ORDER BY substring_index(NodePath,'/',2),NodeID;";
                    }
                    else
                    {
                        QString = "SELECT * FROM tcontent WHERE RecStatus=0 AND (AccessU LIKE '%;guest;%' OR AccessG LIKE '%;Everyone;%' OR AccessG LIKE '%;Guests;%' OR AccessG LIKE '%;Authenticated users;%' " + Session["WhereGroups"] + ") ORDER BY NodePath;"; //"SELECT * FROM tcontent WHERE AccessU LIKE '%;Guest;%' OR AccessG LIKE '%;Everyone;%' OR AccessG LIKE '%;Guests;%' OR AccessG LIKE '%;Authenticated users;%' " + Session["WhereGroups"] + " ORDER BY substring_index(NodePath,'/',2),NodeID;";
                    }
                }
                DataSet ds =GFunc.GetData(QString, "WebCNS",false);
                
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        //DataRow row = ds.Tables[0].Rows[0];

                        foreach (DataRow row in ds.Tables[0].Rows)
                        {
                            if (row["NodePath"].ToString().StartsWith(NodePathLoaded) == false)
                            {
                                if (row["EditU"].ToString().IndexOf(";" + Session["UserName"].ToString() + ";", StringComparison.CurrentCultureIgnoreCase) >= 0)
                                {
                                    UserEditBranch = 1;
                                }
                                TreeNode newnode = new TreeNode(row["TContName"].ToString(), row["NodeID"].ToString());
                                //newnode.ValuePath = row["NodePath"].ToString();
                                newnode.SelectAction = TreeNodeSelectAction.SelectExpand;
                                newnode.NavigateUrl = "main.aspx?ViewID=" + row["ViewID"].ToString() + "&NodePath=" + row["NodePath"].ToString() + "&ViewParam=" + row["ViewParam"].ToString() + "&NodeText=" + newnode.Text.ToLower() + "&UserEditBranch=" + UserEditBranch.ToString();
                                newnode.Target = "main";
                                if (row["ViewID"].ToString() == "3")
                                {
                                    NodePathLoaded = row["NodePath"].ToString();
                                    LoadNodesFromTable(ref newnode, row["NodePath"].ToString(), row["ViewParam"].ToString());

                                }
                                //"main.aspx?ViewID=" + ViewID.Value + "&NodePath=" + NodePath.Value + "&ViewParam=" + ViewParam.Value + "&NodeText=" + tvContent.SelectedNode.Text.ToLower() + ""
                                //newnode.Target = "main";

                                ParentNode = null;
                                if (row["NodePath"].ToString().Length > 3)
                                {
                                    int nstrpos = row["NodePath"].ToString().LastIndexOf("/");
                                    string nstr = row["NodePath"].ToString().Remove(nstrpos);
                                    ParentNode = tvContent.FindNode(nstr);
                                    if (ParentNode != null)
                                    {
                                        ParentNode.ChildNodes.Add(newnode);
                                        //tvContent.Nodes[tvContent.Nodes.IndexOf(ParentNode)].ChildNodes.Add(newnode);
                                    }
                                }
                                else
                                {
                                    tvContent.Nodes.Add(newnode);
                                }
                            }
                        }
                        NameValueCollection HRStr = Request.QueryString;
                        if (HRStr.GetValues("NodeID") != null)
                        {
                            //HtmlTextWriter HTW=new HtmlTextWriter();
                            string[] QS = HRStr.GetValues("NodeID");

                            //string a=HTW.WriteEncodedText(QS);
                            ParentNode = tvContent.FindNode(QS[0]);
                            if (ParentNode != null)
                            {
                                //ParentNode.ExpandAll();
                                ParentNode.Expanded = true;
                                //ParentNode.Select();
                                ParentNode.Selected = true;

                                //tvContent.Nodes[tvContent.Nodes.IndexOf(ParentNode)].ChildNodes.Add(newnode);
                            }

                        }
                        //Session["UserName"] = row["User"];// ds.Tables[0].Columns["User"].ToString();
                        //Session["LongUserName"] = row["LongUsr"]; //ds.Tables[0].Columns["LongUser"].ToString();
                        //return true;
                    }
                    else
                    {
                        //return false;
                    }
                }
            }
            catch (Exception ex)
            {

                // The connection failed. Display an error message.
                //Message.Text = "Unable to connect to the database.";
                Response.Write(ex.Message);

            }
        }

        protected void tvContent_SelectedNodeChanged(object sender, EventArgs e)
        {
            //tvContent.SelectedNode.SelectAction = TreeNodeSelectAction.SelectExpand;
            //tvContent.SelectedNode.Expanded = true;
            //tvContent.SelectedNode.Selected = true;
            //tvContent.SelectedNode.Expand();
            try
            {
                string QString = "SELECT ViewID, ViewParam FROM tcontent  WHERE NodePath='" + tvContent.SelectedNode.ValuePath + "' AND RecStatus=0 ORDER BY NodePath";
                //dsLogin.Select(DataSourceSelectArguments.Empty);

                DataSet ds = GFunc.GetData(QString, "WebCNS", false);
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow row in ds.Tables[0].Rows)
                        {
                            ViewID.Text = row["ViewID"].ToString();
                            ViewParam.Text = row["ViewParam"].ToString();
                        }
                    }
                }

                NodePath.Text = tvContent.SelectedNode.ValuePath;
                //Response.Redirect("main.aspx?ViewID="+ViewID.Value+"&NodePath="+NodePath.Value+"");
                Server.Transfer("main.aspx?ViewID=" + ViewID.Text + "&NodePath=" + NodePath.Text + "&ViewParam=" + ViewParam.Text + "&NodeText=" + tvContent.SelectedNode.Text.ToLower() + "");
                //Submit1.ServerClick;
            }
            catch (Exception ex)
            {

                // The connection failed. Display an error message.
                //Message.Text = "Unable to connect to the database.";
                Response.Write(ex.Message);

            }
        }

        protected void cmdAuth_Click(object sender, EventArgs e)
        {
            if (Session["UserName"] == null || Session["UserName"].ToString() == "" || Session["UserName"].ToString() == "guest")
            {
                Response.Write(@"<script>window.open(""Login.aspx"",""main"");</script>");
            }
            else
            {
                Session.Abandon();
                Response.Write(@"<script>window.open(""Login.aspx"",""main"");</script>");
            }
        }

        protected void cmdAlert_Click(object sender, ImageClickEventArgs e)
        {

        }

        protected void Timer_Tick(object sender, EventArgs e)
        {
            //cmdAlert.CssClass = "cmdAlertNone";
            cmdAlert.Visible = false;
            //cmdAlert.ImageUrl = "";
            //cmdAlert.ToolTip = "";

            if (Session["UserName"] != null & Session["UserName"].ToString() != "" & Session["UserName"].ToString() != "guest")
            {
                string sUName = Session["UserName"].ToString();
                string sQry = "SELECT COUNT(*) as MsgCount FROM Tasks WHERE TaskTo like '%;" + sUName + ";%' and TaskNotify not like '%;" + sUName + ";%'";
                DataSet ds = GFunc.GetData(sQry, "WebCNS", false);
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (Convert.ToInt32(ds.Tables[0].Rows[0]["MsgCount"]) > 0)
                        {
                            //cmdAlert.CssClass = "cmdAlert";
                            cmdAlert.ImageUrl = "Images/Alert.png";
                            cmdAlert.ToolTip = "Ir saņemti " + ds.Tables[0].Rows[0]["MsgCount"].ToString() + " jauni ziņojumi vai uzdevumi.";
                            cmdAlert.Visible = true;
                        }
                    }
                }
            }
        }
    }
}
